﻿using DoNetDrive.Core.Command;
using DoNetDrive.Protocol.Door.Door8800.Data;
using DoNetDrive.Protocol.Door.Door8800.Data.TimeGroup;
using DoNetDrive.Protocol.Door.Door8800.Door;
using DoNetDrive.Protocol.Door.Door8800.Door.OvertimeAlarmSetting;
using DoNetDrive.Protocol.Door.Door8800.Door.ReaderAlarm;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.Alarm;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.BalcklistAlarmOption;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.ControlPanelTamperAlarm;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.FireAlarm;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.FunctionParameter;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.LawfulCardReleaseAlarmSwitch;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.SmogAlarm;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.TheftFortify;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.WorkStatus;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DoNetDrive.Protocol.Door.Test
{
    public partial class frmAlarm : frmNodeForm
    {
        #region 单例模式
        private static object lockobj = new object();
        private static frmAlarm onlyObj;
        public static frmAlarm GetForm(INMain main)
        {
            if (onlyObj == null)
            {
                lock (lockobj)
                {
                    if (onlyObj == null)
                    {
                        onlyObj = new frmAlarm(main);
                        frmMain.AddNodeForms(onlyObj);
                    }
                }
            }
            return onlyObj;
        }

        private frmAlarm(INMain main) : base(main)
        {
            InitializeComponent();

        }
        #endregion

        private void frmAlarm_Load(object sender, EventArgs e)
        {
            var width = (int)(this.Width / 2.1);
            tabControl1.ItemSize = new Size(width, 18);
            LoadUILanguage();

        }
        public override void LoadUILanguage()
        {
            base.LoadUILanguage();

            GetLanguage(tabPage1);
            GetLanguage(tabPage2);
            GetLanguage(groupBox1);
            GetLanguage(groupBox9);
            GetLanguage(groupBox10);
            GetLanguage(groupBox4);
            GetLanguage(groupBox5);
            GetLanguage(groupBox7);
            GetLanguage(groupBox6);
            GetLanguage(groupBox8);
            GetLanguage(label10);
            GetLanguage(BtnSetTheftFortify);
            GetLanguage(BtnSetTheftDisarming);
            GetLanguage(label9);
            GetLanguage(label8);
            GetLanguage(label7);
            GetLanguage(label3);
            GetLanguage(label1);
            GetLanguage(label6);
            GetLanguage(CheckAlarmType1);
            GetLanguage(CheckAlarmType2);
            GetLanguage(CheckAlarmType3);
            GetLanguage(CheckAlarmType4);
            GetLanguage(CheckAlarmType5);
            GetLanguage(CheckAlarmType6);
            GetLanguage(CheckAlarmType7);
            GetLanguage(CheckAlarmType8);
            GetLanguage(CheckAlarmType9);
            GetLanguage(label2);
            GetLanguage(cBoxDoor1);
            GetLanguage(cBoxDoor2);
            GetLanguage(cBoxDoor3);
            GetLanguage(cBoxDoor4);
            GetLanguage(groupBox3);
            GetLanguage(groupBox11);
            GetLanguage(groupBox12);
            GetLanguage(groupBox13);
            GetLanguage(groupBox14);
            GetLanguage(label5);
            GetLanguage(label4);
            GetLanguage(label14);
            GetLanguage(label16);
            GetLanguage(label15);
            GetLanguage(label17);
            GetLanguage(label18);
            GetLanguage(RdoOvertimeAlarmOutEnable);
            GetLanguage(RdoOvertimeAlarmOutDisabled);
            GetLanguage(label20);
            GetLanguage(label19);
            GetLanguage(BtnCloseTypeAlarm);


            var read = GetLanguage("Read");
            var write = GetLanguage("Write");
            var alarm = GetLanguage("Alarm");
            var remove = GetLanguage("Remove");
            var state = GetLanguage("State");
            var enable = GetLanguage("Enable");
            var disabled = GetLanguage("Disabled");
            var begin = GetLanguage("Begin");
            var end = GetLanguage("End");
            var second = GetLanguage("Second");

            BtnReadFireAlarmOption.Text = read;
            BtnReadOpenAlarmOption.Text = read;
            BtnReadSmogAlarmOption.Text = read;
            BtnReadTheftAlarmSetting.Text = read;
            BtnReadBalcklistAlarmOption.Text = read;
            BtnReadLawfulCardReleaseAlarmSwitch.Text = read;
            BtnReadrBtnControlPanelTamperAlarm.Text = read;
            butReadInvalidCardAlarmOption.Text = read;
            BtnReadReaderAlarm.Text = read;
            butReadAlarmPassword.Text = read;
            butReadOvertimeAlarmSetting.Text = read;
            butReadSensorAlarmSetting.Text = read;

            BtnWriteFireAlarmOption.Text = write;
            BtnWriteOpenAlarmOption.Text = write;
            BtnWriteSmogAlarmOption.Text = write;
            BtnWriteTheftAlarmSetting.Text = write;
            BtnWriteBalcklistAlarmOption.Text = write;
            BtnWriteLawfulCardReleaseAlarmSwitch.Text = write;
            BtnWriterBtnControlPanelTamperAlarm.Text = write;
            ButWriteInvalidCardAlarmOption.Text = write;
            Btn_WriteReaderAlarm.Text = write;
            butWriteAlarmPassword.Text = write;
            butWriteOvertimeAlarmSetting.Text = write;
            butWriteSensorAlarmSetting.Text = write;

            BtnAlarm.Text = alarm;
            BtnSmogAlarm.Text = alarm;

            BtnCloseAlarm.Text = remove;
            BtnReadOpenAlarmClose.Text = remove;
            BtnCloseSmogAlarm.Text = remove;

            BtnAlarmState.Text = state;
            //  Btn_OpenAlarmState.Text = state;
            BtnSmogAlarmState.Text = state;
            BtnTheftAlarmSettingState.Text = state;

            rBtnNoTheft.Text = disabled;
            rBtnNoBalcklistAlarm.Text = disabled;
            rBtnNoLawfulCardReleaseAlarmSwitch.Text = disabled;
            rBtnNoControlPanelTamperAlarm.Text = disabled;
            RdoReadInvalidCardAlarmDisabled.Text = disabled;
            RdoReaderAlarmDisabled.Text = disabled;
            RdoAlarmPasswordDisabled.Text = disabled;
            RdoOvertimeAlarmSettingDisabled.Text = disabled;

            rBtnTheft.Text = enable;
            rBtnBalcklistAlarm.Text = enable;
            rBtnLawfulCardReleaseAlarmSwitch.Text = enable;
            rBtnControlPanelTamperAlarm.Text = enable;

            for (int i = 1; i <= 8; i++)
            {
                if (plSensorAlarm.Controls.Find($"Labbegin{i}", true).FirstOrDefault() is Label cbegin)
                {
                    cbegin.Text = begin;
                }
                if (plSensorAlarm.Controls.Find($"Labend{i}", true).FirstOrDefault() is Label cend)
                {
                    cend.Text = end;
                }
            }

            SetComboBox(cbxOption, "cbxOption");
            SetComboBox(cbxPoliceType, "cbxPoliceType");
            SetComboBox(cbxSmogAlarmOption, "cbxSmogAlarmOption");
            SetComboBox(cmbAlarmOption, "AlarmOption");
            SetComboBox(cmbWeek, "WeekOption");
            S_WeekDay = GetLanguage("WeekOption").Split(',');
            cmbReadInvalidCardTime.Items.Clear();
            cmbReadInvalidCardTime.Items.Add("0");
            cbxInTime.Items.Clear();
            cbxOutTime.Items.Clear();
            for (int i = 1; i <= 255; i++)
            {
                var item = $"{i}{second}";
                cmbReadInvalidCardTime.Items.Add(i.ToString());
                cbxInTime.Items.Add(item);
                cbxOutTime.Items.Add(item);
            }
            cmbSensorAlarmSetting.Items.Clear();
            cmbSensorAlarmSetting.Items.Add(enable);
            cmbSensorAlarmSetting.Items.Add(disabled);
            cmbSensorAlarmSetting.SelectedIndex = 0;

            cmbReadInvalidCardTime.SelectedIndex = 0;
            cbxInTime.SelectedIndex = 0;
            cbxOutTime.SelectedIndex = 0;
            SetControlsFont(this.Controls, GetLanguageFont());
        }
        private void SetComboBox(ComboBox comboBox, string languageName)
        {
            comboBox.Items.Clear();
            var texts = GetLanguage(languageName).Split(',');
            foreach (var item in texts)
            {
                comboBox.Items.Add(item);
            }
            comboBox.SelectedIndex = 0;
        }



        private void ForCheckBoxDoorNum(Control control, string findName, Action<int> action)
        {
            for (int i = 1; i <= 4; i++)
            {
                var check = (control.Controls.Find($"{findName}{i}", true).FirstOrDefault() as CheckBox);
                if (check.Checked)
                {
                    action(i);
                }
            }
        }

        #region 消防报警
        /// <summary>
        /// 读取消防报警参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnReadFireAlarmOption_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadFireAlarmOption cmd = new ReadFireAlarmOption(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadFireAlarmOption_Result result = cmde.Command.getResult() as ReadFireAlarmOption_Result;
                int OptionType = result.Option; //消防报警参数
                var OptionTypeStr = GetLanguage("cbxOption").Split(',');

                Invoke(() =>
                {
                    cbxOption.SelectedIndex = OptionType;
                });
                string Info = GetLanguage("groupBox1") + "：" + OptionTypeStr[OptionType];
                mMainForm.AddCmdLog(cmde, Info);
            };
        }
        /// <summary>
        /// 写入消防报警参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnWriteFireAlarmOption_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt16(cbxOption.SelectedIndex) == -1)
            {
                MsgErr(GetLanguage("Msg46"));
                return;
            }
            byte Option = Convert.ToByte(cbxOption.SelectedIndex);
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteFireAlarmOption cmd = new WriteFireAlarmOption(cmdDtl, new WriteFireAlarmOption_Parameter(Option));
            mMainForm.AddCommand(cmd);
        }
        /// <summary>
        /// 触发消防报警
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAlarm_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            SendFireAlarm cmd = new SendFireAlarm(cmdDtl);
            mMainForm.AddCommand(cmd);

        }
        /// <summary>
        /// 关闭消防报警
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnCloseAlarm_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            CloseFireAlarm cmd = new CloseFireAlarm(cmdDtl);
            mMainForm.AddCommand(cmd);
        }
        /// <summary>
        /// 获取消防报警状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAlarmState_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadFireAlarmState cmd = new ReadFireAlarmState(cmdDtl);
            mMainForm.AddCommand(cmd);
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                string ModeStr = cmd.FireAlarmState == 0 ? GetLanguage("Msg49") : GetLanguage("Msg50"); //消防报警状态
                ModeStr = GetLanguage("groupBox1") + "：" + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);
            };
        }
        #endregion

        #region 匪警报警

        private void BtnReadOpenAlarmOption_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadOpenAlarmOption cmd = new ReadOpenAlarmOption(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadOpenAlarmOption_Result result = cmde.Command.getResult() as ReadOpenAlarmOption_Result;
                int OptionType = result.Option; //匪警报警参数
                var OptionTypeStr = GetLanguage("cbxPoliceType").Split(',');

                Invoke(() =>
                {
                    cbxPoliceType.SelectedIndex = OptionType;
                });
                string Info = GetLanguage("groupBox9") + "：" + OptionTypeStr[OptionType];
                mMainForm.AddCmdLog(cmde, Info);
            };
        }

        private void BtnWriteOpenAlarmOption_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt16(cbxPoliceType.SelectedIndex) == -1)
            {
                MsgErr(GetLanguage("Msg56"));
                return;
            }
            byte Option = Convert.ToByte(cbxPoliceType.SelectedIndex);
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteOpenAlarmOption cmd = new WriteOpenAlarmOption(cmdDtl, new WriteOpenAlarmOption_Parameter(Option));
            mMainForm.AddCommand(cmd);
        }

        private void BtnReadOpenAlarmClose_Click(object sender, EventArgs e)
        {
            byte Door = 255; //需要解除报警的门
            byte[] tmpData = new byte[2];
            BitArray bit = new BitArray(tmpData);
            bit[5] = true;
            bit.CopyTo(tmpData, 0);
            ushort AlarmType = BitConverter.ToUInt16(tmpData, 0);
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            CloseAlarm cmd = new CloseAlarm(cmdDtl, new CloseAlarm_Parameter(Door, AlarmType));
            mMainForm.AddCommand(cmd);
        }


        #endregion

        #region 烟雾报警
        private void BtnReadSmogAlarmOption_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadSmogAlarmOption cmd = new ReadSmogAlarmOption(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadSmogAlarmOption_Result result = cmde.Command.getResult() as ReadSmogAlarmOption_Result;
                int OptionType = result.Option; //烟雾报警参数
                var OptionTypeStr = GetLanguage("cbxSmogAlarmOption").Split(',');

                Invoke(() =>
                {
                    cbxSmogAlarmOption.SelectedIndex = OptionType;
                });
                string Info = GetLanguage("groupBox10") + "：" + OptionTypeStr[OptionType];
                mMainForm.AddCmdLog(cmde, Info);
            };
        }

        private void BtnWriteSmogAlarmOption_Click(object sender, EventArgs e)
        {
            byte Option = Convert.ToByte(cbxSmogAlarmOption.SelectedIndex);
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteSmogAlarmOption cmd = new WriteSmogAlarmOption(cmdDtl, new WriteSmogAlarmOption_Parameter(Option));
            mMainForm.AddCommand(cmd);
        }

        private void BtnSmogAlarm_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            SendSmogAlarm cmd = new SendSmogAlarm(cmdDtl);
            mMainForm.AddCommand(cmd);

        }

        private void BtnCloseSmogAlarm_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            CloseSmogAlarm cmd = new CloseSmogAlarm(cmdDtl);
            mMainForm.AddCommand(cmd);

        }

        private void BtnSmogAlarmState_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadSmogAlarmState cmd = new ReadSmogAlarmState(cmdDtl);
            mMainForm.AddCommand(cmd);
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                string ModeStr = cmd.SmogAlarmState == 0 ? GetLanguage("Msg49") : GetLanguage("Msg50"); //烟雾报警状态

                ModeStr = GetLanguage("groupBox10") + "：" + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);

            };
        }

        #endregion

        #region 防盗报警
        /// <summary>
        /// 读取参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnReadTheftAlarmSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadTheftAlarmSetting cmd = new ReadTheftAlarmSetting(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadTheftAlarmSetting_Result result = cmde.Command.getResult() as ReadTheftAlarmSetting_Result;
                string useStr = result.Setting.Use ? GetLanguage("Enable") : GetLanguage("Disabled"); //功能开关
                string beginPassword = result.Setting.BeginPassword.ToString(); //布防密码
                string closePassword = result.Setting.ClosePassword.ToString(); //撤防密码

                Invoke(() =>
                {
                    if (result.Setting.Use)
                    {
                        rBtnTheft.Checked = true;
                    }
                    else
                    {
                        rBtnNoTheft.Checked = true;
                    }
                    cbxInTime.SelectedIndex = result.Setting.InTime - 1;
                    cbxOutTime.SelectedIndex = result.Setting.OutTime - 1;
                    Num_AlarmTime.Value = result.Setting.AlarmTime;
                    txtBeginPassword.Text = beginPassword;
                    txtClosePassword.Text = closePassword;
                });
                var time = GetLanguage("Second");
                string TheftAlarmSettingInfo = GetLanguage("label10") + useStr + Environment.NewLine +
                                               GetLanguage("label9") + result.Setting.InTime + time + Environment.NewLine +
                                               GetLanguage("label8") + result.Setting.OutTime + time + Environment.NewLine +
                                               GetLanguage("label3") + result.Setting.AlarmTime + time + Environment.NewLine +
                                               GetLanguage("label7") + beginPassword + Environment.NewLine +
                                               GetLanguage("label6") + closePassword;
                mMainForm.AddCmdLog(cmde, TheftAlarmSettingInfo);
            };
        }
        /// <summary>
        /// 写入参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnWriteTheftAlarmSetting_Click(object sender, EventArgs e)
        {
            string reg = @"^\+?[0-9]*$";
            if (!Regex.IsMatch(txtBeginPassword.Text.Trim(), reg))
            {
                MsgErr(GetLanguage("Msg89") + "！");
                return;
            }
            if (txtBeginPassword.Text.Trim().Length > 8)
            {
                MsgErr(GetLanguage("Msg90") + "！");
                return;
            }
            if (!Regex.IsMatch(txtClosePassword.Text.Trim(), reg))
            {
                MsgErr(GetLanguage("Msg91") + "！");
                return;
            }
            if (txtClosePassword.Text.Trim().Length > 8)
            {
                MsgErr(GetLanguage("Msg92") + "！");
                return;
            }

            TheftAlarmSetting ts = new TheftAlarmSetting();
            ts.Use = rBtnTheft.Checked;
            ts.InTime = Convert.ToUInt16(cbxInTime.SelectedIndex + 1);
            ts.OutTime = Convert.ToUInt16(cbxOutTime.SelectedIndex + 1);
            ts.AlarmTime = (ushort)Num_AlarmTime.Value;
            if (ts.AlarmTime > 255)
            {
                ts.AlarmTime = 65535;
            }
            ts.BeginPassword = txtBeginPassword.Text;
            ts.ClosePassword = txtClosePassword.Text;
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteTheftAlarmSetting cmd = new WriteTheftAlarmSetting(cmdDtl, new WriteTheftAlarmSetting_Parameter(ts));
            mMainForm.AddCommand(cmd);
        }
        /// <summary>
        /// 布防
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSetTheftFortify_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            SetTheftFortify cmd = new SetTheftFortify(cmdDtl);
            mMainForm.AddCommand(cmd);

        }
        /// <summary>
        /// 撤防
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSetTheftDisarming_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            SetTheftDisarming cmd = new SetTheftDisarming(cmdDtl);
            mMainForm.AddCommand(cmd);
        }
        /// <summary>
        /// 状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnTheftAlarmSettingState_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadTheftAlarmState cmd = new ReadTheftAlarmState(cmdDtl);
            mMainForm.AddCommand(cmd);
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadTheftAlarmState_Result result = cmde.Command.getResult() as ReadTheftAlarmState_Result;
                StringBuilder TheftStateInfo = new StringBuilder();
                TheftStateInfo.Append(GetLanguage("Msg154") + "：");
                string TheftStateStr = string.Empty;
                Invoke(() =>
                {
                    if (result.TheftState == 1)
                    {
                        TheftStateStr = GetLanguage("Msg148");
                    }
                    else if (result.TheftState == 2)
                    {
                        TheftStateStr = GetLanguage("Msg149");
                    }
                    else if (result.TheftState == 3)
                    {
                        TheftStateStr = GetLanguage("Msg150");
                    }
                    else if (result.TheftState == 4)
                    {
                        TheftStateStr = GetLanguage("Msg151");
                    }
                    else if (result.TheftState == 5)
                    {
                        TheftStateStr = GetLanguage("Msg152");
                    }
                    else if (result.TheftState == 6)
                    {
                        TheftStateStr = GetLanguage("Msg153");
                    }
                    txtBeginState.Text = TheftStateStr;
                    TheftStateInfo.Append(TheftStateStr);
                    mMainForm.AddCmdLog(cmde, TheftStateInfo.ToString());
                });
            };
        }

        #endregion

        #region 黑名单
        private void BtnReadBalcklistAlarmOption_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadBalcklistAlarmOption cmd = new ReadBalcklistAlarmOption(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadBalcklistAlarmOption_Result result = cmde.Command.getResult() as ReadBalcklistAlarmOption_Result;
                string ModeStr = result.Use == 0 ? GetLanguage("Disabled") : GetLanguage("Enable"); //黑名单报警功能是否启用
                Invoke(() =>
                {
                    if (result.Use == 0)
                    {
                        rBtnNoBalcklistAlarm.Checked = true;
                    }
                    else
                    {
                        rBtnBalcklistAlarm.Checked = true;
                    }
                });
                ModeStr = GetLanguage("groupBox5") + "：" + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);
            };


        }

        private void BtnWriteBalcklistAlarmOption_Click(object sender, EventArgs e)
        {
            byte use = 0;
            if (rBtnBalcklistAlarm.Checked == true)
            {
                use = 1;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteBalcklistAlarmOption cmd = new WriteBalcklistAlarmOption(cmdDtl, new WriteBalcklistAlarmOption_Parameter(use));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 合法卡解除报警开关
        private void BtnReadLawfulCardReleaseAlarmSwitch_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadLawfulCardReleaseAlarmSwitch cmd = new ReadLawfulCardReleaseAlarmSwitch(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadLawfulCardReleaseAlarmSwitch_Result result = cmde.Command.getResult() as ReadLawfulCardReleaseAlarmSwitch_Result;
                string ModeStr = result.Use == 0 ? GetLanguage("Disabled") : GetLanguage("Enable"); //合法卡解除报警开关是否启用
                Invoke(() =>
                {
                    if (result.Use == 0)
                    {
                        rBtnNoLawfulCardReleaseAlarmSwitch.Checked = true;
                    }
                    else
                    {
                        rBtnLawfulCardReleaseAlarmSwitch.Checked = true;
                    }
                });
                ModeStr = GetLanguage("groupBox7") + "：" + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);

            };
        }

        private void BtnWriteLawfulCardReleaseAlarmSwitch_Click(object sender, EventArgs e)
        {
            byte use = 0;
            if (rBtnLawfulCardReleaseAlarmSwitch.Checked == true)
            {
                use = 1;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteLawfulCardReleaseAlarmSwitch cmd = new WriteLawfulCardReleaseAlarmSwitch(cmdDtl, new WriteLawfulCardReleaseAlarmSwitch_Parameter(use));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 控制板防拆报警开关
        private void BtnReadrBtnControlPanelTamperAlarm_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadControlPanelTamperAlarm cmd = new ReadControlPanelTamperAlarm(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadControlPanelTamperAlarm_Result result = cmde.Command.getResult() as ReadControlPanelTamperAlarm_Result;
                string ModeStr = result.Use == 0 ? GetLanguage("Disabled") : GetLanguage("Enable"); //控制板防拆报警开关是否启用
                Invoke(() =>
                {
                    if (result.Use == 0)
                    {
                        rBtnNoControlPanelTamperAlarm.Checked = true;
                    }
                    else
                    {
                        rBtnControlPanelTamperAlarm.Checked = true;
                    }
                });
                ModeStr = GetLanguage("groupBox6") + "：" + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);
            };
        }

        private void BtnWriterBtnControlPanelTamperAlarm_Click(object sender, EventArgs e)
        {
            byte use = 0;
            if (rBtnControlPanelTamperAlarm.Checked == true)
            {
                use = 1;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteControlPanelTamperAlarm cmd = new WriteControlPanelTamperAlarm(cmdDtl, new WriteControlPanelTamperAlarm_Parameter(use));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 解除所有报警
        private void BtnCloseTypeAlarm_Click(object sender, EventArgs e)
        {
            byte Door = 255; //需要解除报警的门
            byte[] tmpData = new byte[2];
            BitArray bit = new BitArray(tmpData);
            for (int i = 0; i < 9; i++)
            {
                var check = (this.groupBox8.Controls.Find($"CheckAlarmType{i + 1}", true).FirstOrDefault() as CheckBox);
                if (check != null)
                {
                    bit[i] = check.Checked;
                }
            }
            bit.CopyTo(tmpData, 0);
            ushort AlarmType = BitConverter.ToUInt16(tmpData, 0);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            CloseAlarm cmd = new CloseAlarm(cmdDtl, new CloseAlarm_Parameter(Door, AlarmType));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 读卡器防拆报警
        private void BtnReadReaderAlarm_Click(object sender, EventArgs e)
        {
            ForAlarmDoorNum((doorNum) =>
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                if (cmdDtl == null) return;
                var parameter = new DoorPort_Parameter(doorNum);
                var cmd = new ReadReaderAlarm(cmdDtl, parameter);
                cmdDtl.CommandCompleteEvent += (s, c) =>
                {
                    var result = (ReaderAlarm_Result)c.Result;
                    Invoke(() =>
                    {
                        if (result.Use == 1)
                            RdoReaderAlarmEnable.Checked = true;
                        else
                            RdoReaderAlarmDisabled.Checked = true;
                        var use = RdoReaderAlarmEnable.Checked ? GetLanguage("Disabled") : GetLanguage("Enable");
                        mMainForm.AddCmdLog(c, $"{GetLanguage("label2")}:{doorNum}，{GetLanguage("label4")}{use}");
                    });
                };
                mMainForm.AddCommand(cmd);
            });

        }

        private void Btn_WriteReaderAlarm_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForAlarmDoorNum((doorNum) =>
            {
                byte use = (byte)(RdoReaderAlarmEnable.Checked ? 1 : 0);
                var parameter = new WriteReaderAlarm_Parameter((byte)doorNum, use);
                var cmd = new WriteReaderAlarm(cmdDtl, parameter);
                mMainForm.AddCommand(cmd);
            });

        }
        private void ForAlarmDoorNum(Action<int> action)
        {
            ForCheckBoxDoorNum(tableLayoutPanel10, "cBoxDoor", action);
        }

        #endregion

        #region 读非法卡报警
        private void butReadInvalidCardAlarmOption_Click(object sender, EventArgs e)
        {
            ForAlarmDoorNum((doorNum) =>
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                var par = new Door8800.Door.DoorPort_Parameter(doorNum);
                if (!mMainForm.CheckProtocolTypeIs89H())
                {
                    var cmd = new Door8800.Door.InvalidCardAlarmOption.ReadInvalidCardAlarmOption(cmdDtl, par);
                    mMainForm.AddCommand(cmd);
                }
                else
                {
                    var cmd = new Door89H.Door.InvalidCardAlarmOption.ReadInvalidCardAlarmOption(cmdDtl, par);
                    mMainForm.AddCommand(cmd);
                }
                cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
                {
                    var result = cmde.Command.getResult() as Door8800.Door.InvalidCardAlarmOption.InvalidCardAlarmOption_Result;
                    Invoke(() =>
                    {
                        RdoReadInvalidCardAlarmEnable.Checked = result.Use;
                        RdoReadInvalidCardAlarmDisabled.Checked = !result.Use;
                        cmbReadInvalidCardTime.SelectedIndex = result.ReadInvalidCardTime;
                    });
                    var use = result.Use ? GetLanguage("Disabled") : GetLanguage("Enable");
                    mMainForm.AddCmdLog(cmde, $"{GetLanguage("label2")}:{result.DoorNum}{Environment.NewLine}{GetLanguage("label10")}:{use}{Environment.NewLine}{GetLanguage("label5")}" + result.ReadInvalidCardTime);
                };

            });
        }

        private void ButWriteInvalidCardAlarmOption_Click(object sender, EventArgs e)
        {
            bool use = RdoReadInvalidCardAlarmEnable.Checked;
            var cmdDtl = mMainForm.GetCommandDetail();
            var time = (byte)cmbReadInvalidCardTime.SelectedIndex;
            ForAlarmDoorNum((doorNum) =>
            {
                byte door = (byte)doorNum;
                var par = new Door8800.Door.InvalidCardAlarmOption.WriteInvalidCardAlarmOption_Parameter(door, use, time);
                INCommand cmd;
                if (!mMainForm.CheckProtocolTypeIs89H())
                {
                    cmd = new Door8800.Door.InvalidCardAlarmOption.WriteInvalidCardAlarmOption(cmdDtl, par);
                }
                else
                {
                    cmd = new Door89H.Door.InvalidCardAlarmOption.WriteInvalidCardAlarmOption(cmdDtl, par);
                }
                mMainForm.AddCommand(cmd);
            });

        }

        #endregion
        #region 胁迫报警密码
        private void butReadAlarmPassword_Click(object sender, EventArgs e)
        {
            ForAlarmDoorNum((doorNum) =>
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                var par = new Door8800.Door.DoorPort_Parameter(doorNum);
                var cmd = new Door8800.Door.AlarmPassword.ReadAlarmPassword(cmdDtl, par);
                mMainForm.AddCommand(cmd);
                cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
                {
                    var result = cmd.getResult() as Door8800.Door.AlarmPassword.AlarmPassword_Result;
                    Invoke(() =>
                    {

                        RdoAlarmPasswordEnable.Checked = result.Use;
                        RdoAlarmPasswordDisabled.Checked = !result.Use;
                        cmbAlarmOption.SelectedIndex = (result.AlarmOption - 1);
                        Txt_Password.Text = result.Password;
                    });
                    var use = result.Use ? GetLanguage("Disabled") : GetLanguage("Enable");
                    var option = GetLanguage("AlarmOption").Split(',');
                    mMainForm.AddCmdLog(cmde, $"{GetLanguage("label2")}:{result.DoorNum}{Environment.NewLine}{GetLanguage("label4")}{use}{Environment.NewLine}{GetLanguage("label15")}{result.Password}{Environment.NewLine}{GetLanguage("label16")}{option[result.AlarmOption - 1]}");
                };

            });
        }
        private void butWriteAlarmPassword_Click(object sender, EventArgs e)
        {
            var alarmOption = cmbAlarmOption.SelectedIndex + 1;
            var password = Txt_Password.Text;
            if (string.IsNullOrWhiteSpace(password))
            {
                MessageBox.Show("胁迫报警密码不能为空");
                return;
            }
            var use = RdoAlarmPasswordEnable.Checked;
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForAlarmDoorNum((doorNum) =>
            {
                var par = new Door8800.Door.AlarmPassword.WriteAlarmPassword_parameter((byte)doorNum, use, password, alarmOption);
                var cmd = new Door8800.Door.AlarmPassword.WriteAlarmPassword(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });
        }
        #endregion

        #region 开门超时提示参数
        private void butReadOvertimeAlarmSetting_Click(object sender, EventArgs e)
        {
            ForAlarmDoorNum((doorNum) =>
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                var par = new DoorPort_Parameter(doorNum);
                var cmd = new ReadOvertimeAlarmSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
                cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
                {
                    var result = cmd.getResult() as OvertimeAlarmSetting_Result;
                    Invoke(() =>
                    {
                        RdoOvertimeAlarmSettingEnable.Checked = result.Use;
                        RdoOvertimeAlarmSettingDisabled.Checked = !result.Use;
                        Num_OverTime.Value = result.Overtime;
                        RdoOvertimeAlarmOutEnable.Checked = result.Alarm;
                        RdoOvertimeAlarmOutDisabled.Checked = !result.Alarm;
                    });
                    string usetip = result.Use ? GetLanguage("Enable") : GetLanguage("Disabled");
                    string Alarmtip = result.Alarm ? GetLanguage("RdoOvertimeAlarmOutDisabled") : GetLanguage("RdoOvertimeAlarmOutEnable");
                    mMainForm.AddCmdLog(cmde, $"{GetLanguage("label2")}：{result.DoorNum}{Environment.NewLine}{GetLanguage("label10")}:{usetip}{Environment.NewLine}{GetLanguage("label17")}：{result.Overtime}{Environment.NewLine}{GetLanguage("label18")} {Alarmtip.Replace(":", "")}");
                };
            });

        }

        private void butWriteOvertimeAlarmSetting_Click(object sender, EventArgs e)
        {
            var use = RdoOvertimeAlarmSettingEnable.Checked;
            var alarm = RdoOvertimeAlarmOutEnable.Checked;
            var overtime = (ushort)Num_OverTime.Value;
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForAlarmDoorNum((doorNum) =>
            {
                var par = new WriteOvertimeAlarmSetting_Parameter((byte)doorNum, use, overtime, alarm);
                var cmd = new WriteOvertimeAlarmSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });
        }
        #endregion

        #region 门磁报警参数

        WeekTimeGroup WeekTimeGroupSensorAlarmDto = new WeekTimeGroup(8);
        private void butReadSensorAlarmSetting_Click(object sender, EventArgs e)
        {
            ForAlarmDoorNum((doorNum) =>
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                if (cmdDtl == null) return;
                var par = new Door8800.Door.DoorPort_Parameter(doorNum);
                var cmd = new Door8800.Door.SensorAlarmSetting.ReadSensorAlarmSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
                cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
                {
                    var result = cmd.getResult() as Door8800.Door.SensorAlarmSetting.SensorAlarmSetting_Result;
                    Invoke(() =>
                    {
                        WeekTimeGroupSensorAlarmDto = result.WeekTimeGroup;
                        var day = WeekTimeGroupSensorAlarmDto.GetItem(cmbWeek.SelectedIndex);
                        SetAllTimePicker(plSensorAlarm, "beginSATP", "endSATP", day);
                        cmbSensorAlarmSetting.SelectedIndex = result.Use ? 0 : 1;
                    });
                    string ModeStr = result.Use ? GetLanguage("Enable") : GetLanguage("Disabled");
                    mMainForm.AddCmdLog(cmde, GetWeekTimeGroupString(WeekTimeGroupSensorAlarmDto));
                    mMainForm.AddCmdLog(cmde, $"{GetLanguage("label2")}:{result.DoorNum}{Environment.NewLine}{GetLanguage("label4")}{ModeStr}");

                };
            });
        }

        private void butWriteSensorAlarmSetting_Click(object sender, EventArgs e)
        {
            ForAlarmDoorNum((doorNum) =>
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                bool use = (cmbSensorAlarmSetting.SelectedIndex == 0);
                byte door = (byte)doorNum;
                var par = new Door8800.Door.SensorAlarmSetting.WriteSensorAlarmSetting_Parameter(door, use, WeekTimeGroupSensorAlarmDto);
                var cmd = new Door8800.Door.SensorAlarmSetting.WriteSensorAlarmSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });



        }
        static string[] S_WeekDay = new string[] { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日", };
        //static string[] S_Title = new string[] { "第一时段", "第二时段", "第三时段", "第四时段", "第五时段", "第六时段", "第七时段", "第八时段" };
        /// <summary>
        /// 
        /// </summary>
        /// <param name="weekTimeGroup"></param>
        /// <returns></returns>
        private string GetWeekTimeGroupString(WeekTimeGroup weekTimeGroup)
        {
            StringBuilder sb = new StringBuilder();
            string def = "       ";
            for (int i = 0; i < 7; i++)
            {
                var day = weekTimeGroup.GetItem(i);
                sb.Append($"{S_WeekDay[i]}:");
                for (int j = 0; j < 8; j++)
                {
                    var time = day.GetItem(j);
                    var sTime = ($"{time.GetBeginTime():HH:mm}--{time.GetEndTime():HH:mm}; ");
                    if (j == 4)
                    {
                        sb.AppendLine();
                        sb.Append(def + sTime);
                    }
                    else
                    {
                        sb.Append(sTime);
                    }
                }
                sb.AppendLine();
                sb.AppendLine();
            }
            return sb.ToString();
        }
        /// <summary>
        /// 结束时间更变时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EndSATP_ValueChanged(object sender, EventArgs e)
        {
            DateTimePicker dtp = sender as DateTimePicker;
            SetWeekTimeGroupValue(WeekTimeGroupSensorAlarmDto, cmbWeek.SelectedIndex, int.Parse(dtp.Name.Substring(dtp.Name.Length - 1)) - 1, 2, dtp.Value);
        }
        /// <summary>
        /// 开始时间更变时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BeginTimePicker_ValueChanged(object sender, EventArgs e)
        {
            DateTimePicker dtp = sender as DateTimePicker;
            SetWeekTimeGroupValue(WeekTimeGroupSensorAlarmDto, cmbWeek.SelectedIndex, int.Parse(dtp.Name.Substring(dtp.Name.Length - 1)) - 1, 1, dtp.Value);
        }
        /// <summary>
        /// 重新选择星期的时候更变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbWeek_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (WeekTimeGroupSensorAlarmDto != null)
            {
                var day = WeekTimeGroupSensorAlarmDto.GetItem(cmbWeek.SelectedIndex);
                SetAllTimePicker(plSensorAlarm, "beginSATP", "endSATP", day);
            }
        }
        #endregion
    }
}
